#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <string>
#include <cstring>
#define N 2
#define NUM 1024

void Cwrite(int fd)
{
    const char* s = "一酷酷哒哟";
    char buff[NUM];
    int number = 0;
    while(true)
    {
        buff[0] = 0;
        snprintf(buff,sizeof(buff),"写入的内容是:%s,写入的次数是:%d",s,number++);
        write(fd,buff,strlen(buff));
        sleep(1);
    }

}

void Fread(int fd)
{
    char buff[NUM];
    while(true)
    {
        read(fd,buff,sizeof(buff));
        std::cout << buff << std::endl;
    }
}


int main()
{
    int fdarr[N];
    int ret = pipe(fdarr);//0读1写
    if(ret < 0)
    {
        perror("pipe");
        exit(EXIT_FAILURE);   
    }

    pid_t pid = fork();
    if(pid < 0)
    {
        perror("fork");
        exit(EXIT_FAILURE);
    }
    else if(pid == 0)
    {
        close(fdarr[0]);
        Cwrite(fdarr[1]);
        close(fdarr[1]);
    }

    close(fdarr[1]);//关闭写端

    Fread(fdarr[0]);
    pid_t retpid = waitpid(pid,nullptr,0);
    if(retpid != pid)
    {
        perror("wait");
        exit(EXIT_FAILURE);
    }
    
    close(fdarr[0]);


    return 0;
}